<?php
namespace drivers;
use func\MySQL;

abstract class Model
{
    private $db;

    private $table;

    /**
     * @return string
     */
    public function getTable()
    {
        return $this->table;
    }

    /**
     * @param string $table
     */
    public function setTable($table)
    {
        $this->table = $table;
    }

    /**
     * @return mixed
     */
    public function getDb()
    {
        if(!isset($this->db)&&empty($this->db))
        {
            $config = factory::config()->getConfig('database');
            $this->db = new MySQL($config);
        }
        return $this->db;
    }


    //增加
    function insert($values,$fild = '')
    {
        if(!empty($fild))
        {
            $sql = "INSERT INTO ".$this->getTable()." ($fild) VALUES ($values)";
        }
        else
        {
            $sql = "INSERT INTO ".$this->getTable()." VALUES ($values)";
        }
        return $this->getDb()->sql_query($sql);
    }

    //删除
    function delete($where)
    {
        $sql = "DELETE FROM ".$this->getTable()."WHERE $where";
        return $this->getDb()->sql_query($sql);
    }

    //修改
    function update($SET)
    {
        $sql = "UPDATE ".$this->getTable()." SET $SET";
        return $this->getDb()->sql_query($sql);
    }

    //查询
    function select($other = '',$field = '*')
    {
        $sql = "SELECT $field FROM ".$this->getTable()." $other";

        return $this->getDb()->select($sql);
    }


    //验证非法表单
    function validate_form($data,$model,$func,$href='?c=index')
    {
        if(isset($data['token'])&&isset($_SESSION['token']))
        {
            if($data['token'] == $_SESSION['token'])
            {
                unset($data['token']);
                $func($data,$model);
            }
            else
            {
                exit('<script>alert(\'非法的表单\');location.href="'.$href.'"</script>');
            };

        }
        else
        {
            exit('<script>alert(\'非法的表单\');location.href="'.$href.'"</script>');
        };
        unset($_SESSION['token']);
    }

}